﻿using Dapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TodoApp.EntityFrameworkCore;
using TodoApp.ResultModel;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Domain.Repositories.Dapper;
using Volo.Abp.EntityFrameworkCore;

namespace TodoApp.TMS_settlement.Payments
{
    public class TMS_PaymentRepository : DapperRepository<TodoAppDbContext>, ITransientDependency, ITMS_PaymentRepository
    {
        public TMS_PaymentRepository(IDbContextProvider<TodoAppDbContext> dbContextProvider) : base(dbContextProvider)
        {
        }

        public async Task<int> CreatePayment(TMS_Payment tMS_Payment)
        {
            var dbConnection = await GetDbConnectionAsync();
            return await dbConnection.ExecuteAsync($"", null, await GetDbTransactionAsync());
        }

        public async Task<int> DeletePayment(string id)
        {
            var dbConnection = await GetDbConnectionAsync();
            var count = 0;
            var ids = id.Split(',');
            foreach (var item in ids)
            {
                var sql = $"update TMS_Payment set Payment_Delete='false' where Id='{item}'";
                count += await dbConnection.ExecuteAsync(sql, null,
                 await GetDbTransactionAsync());
            }
            return count;
        }

        public async Task<PageResponse<TMS_PaymentDto>> GetPayment(string name, string date, bool? state, int pageindex, int pagesize)
        {
            PageResponse<TMS_PaymentDto> response = new PageResponse<TMS_PaymentDto>();
            var dbConnection = await GetDbConnectionAsync();
            var sql = "select * from TMS_Payment a left join TMS_Employees b on a.Payment_CheckPeople=b.Id where Payment_Delete='true'";
            var list = await dbConnection.QueryAsync<TMS_PaymentDto>(sql, transaction: await GetDbTransactionAsync());
            response.PageTotal = list.Count();
            if (name != null)
            {
                sql += $" and a.Payment_Title = '{name}'";
            }
            if (date != null)
            {
                sql += $" and a.Payment_DateTime = '{date}'";
            }
            if (state != null)
            {
                sql += $" and a.Payment_CheckState = '{state}'";
            }
            sql += $" order by a.Payment_DateTime offset {(pageindex - 1) * pagesize} rows fetch next {pagesize} rows only";
            var lists = await dbConnection.QueryAsync<TMS_PaymentDto>(sql, transaction: await GetDbTransactionAsync());
            response.PageData = lists.ToList();
            return response;
        }

        public async Task<int> UpdatePayment(TMS_Payment tMS_Payment)
        {
            throw new NotImplementedException();
        }
    }
}
